import type { IChildInfo } from '@/api/child'
import { deepClone } from '@alova/shared'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getChild } from '@/api/child'

export const useChildStore = defineStore(
  'child',
  () => {
    const childLists = ref<IChildInfo[]>([])

    const selectedChild = ref<IChildInfo | null>(null)

    const childMap = computed(() => {
      const map = new Map<string, string>()
      childLists.value.forEach((item) => {
        map.set(item.id, item.name)
      })
      return map
    })

    const toggleSelectedChild = (child: IChildInfo) => {
      selectedChild.value = deepClone(child)
    }

    const removeChild = (id: Pick<IChildInfo, 'id'>) => {
      childLists.value = childLists.value.filter(item => item.id !== id.id)
    }

    const fetchChildList = async () => {
      const res = await getChild()
      if (res.length) {
        if (!Object.keys(selectedChild.value || {}).length) {
          selectedChild.value = res[0]
        }
        else {
          selectedChild.value = res.filter(item => item.id === selectedChild.value.id)[0]
        }
      }
      childLists.value = res
      console.log('获取孩子列表成功:', childLists.value)
      return res
    }

    return {
      childLists,
      selectedChild,
      childMap,
      toggleSelectedChild,
      removeChild,
      fetchChildList,
    }
  },
  {
    persist: true,
  },
)
